import axios from 'axios';
import ENV from '../config/ENV';
import { message } from 'ant-design-vue';
import sm4 from '@/utils/sm4';
import { isString } from '../utils/is';
import HttpCode from '@/constants/HttpCode';
import { useUserStore } from '@/store';
import router from "@/router";

const axiosInstance = axios.create({
    baseURL: ENV.REQUEST_URL, 
    timeout: 10000,
    method: 'post',
});

// Request interceptor
axiosInstance.interceptors.request.use(
    config => {
        const token = useUserStore().token;
        if (token) {
            config.headers[ENV.TOKEN_NAME] = token;
        }

        if (!config.data)
            config.data = {};
    
        if (!(config.data instanceof FormData)) {
            config.headers['Content-Type'] = 'application/json';
            console.log(`${config.url}====> 请求参数：`, config.data);
            config.data = sm4.encrypt(JSON.stringify(config.data));
        }
    
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// Response interceptor
axiosInstance.interceptors.response.use(
    response => {
        if (response.status !== 200) {
            message.error('网络开小差啦！请稍后重试。');
            return Promise.reject();
        }

        if (response.data instanceof ArrayBuffer || response.data instanceof Blob) {
            return Promise.resolve(response);
        }

        if (isString(response.data))
            response.data = JSON.parse(sm4.decrypt(response.data));
        console.log(`${response.config.url} ====> 响应参数:`, response.data);
        const { code, success, status } = response.data;
        switch (code) {
            case HttpCode.Success:
                return Promise.resolve(response.data);
            case HttpCode.Error:
                if (status === 305) {
                    router.replace('/login');
                }
                message.error(response.data.message);
                return Promise.reject(response.data.message);
            case HttpCode.Exception:
                return Promise.reject(response.data.message);
            case HttpCode.Authorization:
                message.warning('身份认证失败，请重新登录');
                router.replace('/login');
                return Promise.reject();
            default:
                return Promise.reject();
        }
    },
    error => {
        console.log(error);
        const { url } = error.config;
        message.error('网络开小差啦，请稍后重试');
        return Promise.reject('网络开小差啦，请稍后重试');
    }
);

export default axiosInstance;